#!/usr/bin/env bash
# Copyright (c) 2021 The Toltec Contributors
# SPDX-License-Identifier: MIT
archs=(rm1os2 rm2os2)
pkgnames=(wireguard)
pkgdesc="Fast, modern, secure VPN tunnel"
url=https://www.wireguard.com
pkgver=1.0.20220627-1
timestamp=2021-02-19T14:08Z
section=kernel
maintainer="Jonah Weissman <jonahrweissman+toltec@gmail.com>"
license=GPL-2.0-only
makedepends=(build:bc build:lzop build:git build:flex build:bison build:libssl-dev)
flags=(nostrip)
installdepends=(wireguard-tools)

_kernelrepo=https://github.com/remarkable/linux
_kernelrevs=(
    bb6be69d6f71fced2fc63c61372bf96e5f7da565
    bb6be69d6f71fced2fc63c61372bf96e5f7da565
)
_defconfigs=(
    arch/arm/configs/zero-gravitas_defconfig
    arch/arm/configs/zero-sugar_defconfig
)

image=base:v3.2
source=(
    "https://git.zx2c4.com/wireguard-linux-compat/snapshot/wireguard-linux-compat-${pkgver%-*}.tar.xz"
    fix-multiple-yylloc-definitions.patch
)
sha256sums=(
    362d412693c8fe82de00283435818d5c5def7f15e2433a07a9fe99d0518f63c0
    SKIP
)

build() {
    mkdir pkg
    git init linux
    for i in $(seq 0 1); do
        (
            cd linux
            git fetch --depth=1 "$_kernelrepo" "${_kernelrevs[$i]}"
            git checkout -f "${_kernelrevs[$i]}"
            git apply "$srcdir"/fix-multiple-yylloc-definitions.patch || true
            make mrproper
            touch .scmversion
            cp "${_defconfigs[$i]}" .config
            echo "CONFIG_NET_FOU=m" >> .config
            make olddefconfig
            make net/ipv4/udp_tunnel.ko
            make net/ipv6/ip6_udp_tunnel.ko
            make modules_prepare
        )

        make -C src/ "KERNELDIR=$(realpath linux)"
        KERNELRELEASE=$(cat linux/include/config/kernel.release)
        export MOD_INSTALL_PATH="pkg/$KERNELRELEASE"
        install -D -m 644 linux/net/ipv4/udp_tunnel.ko \
            "$MOD_INSTALL_PATH/kernel/net/ipv4/udp_tunnel.ko"
        install -D -m 644 linux/net/ipv6/ip6_udp_tunnel.ko \
            "$MOD_INSTALL_PATH/kernel/net/ipv6/ip6_udp_tunnel.ko"
        install -D -m 644 src/wireguard.ko \
            "$MOD_INSTALL_PATH/extra/wireguard.ko"
    done
}

package() {
    mkdir -p "$pkgdir/lib/modules"
    cp -r "$srcdir/pkg"/* "$pkgdir/lib/modules"
}

configure() {
    depmod -a
}

postremove() {
    cat << MSG
Wireguard has been removed.
The kernel module will remain loaded until you reboot, or you can attempt
to manually remove it by running "modprobe -r wireguard".
MSG
    depmod -a
}

postupgrade() {
    cat << MSG
Wireguard has been upgraded.
The old kernel module will remain loaded until you reboot, or you can
attempt to manually remove it by running "modprobe -r wireguard".
MSG
}
